#include <bits/stdc++.h>

using namespace std;

// 满足不等式的数对数目
// 测试链接：https://leetcode.cn/problems/number-of-pairs-satisfying-inequality/

class Solution 
{
private:
    int tmp[100010];
    int diff;

    long long merge(vector<int>& nums, int l, int m, int r)
    {
        // 统计部分
        long long ret = 0;
        for(int i = l, j = m + 1; j <= r; ++j)
        {
            while(i <= m && nums[i] <= nums[j] + diff) ++i;
            ret += i - l;
        }

        // 正常的 merge 过程
        int i = l, a = l, b = m + 1;
        while(a <= m && b <= r)
        {
            tmp[i++] = nums[a] <= nums[b] ? nums[a++] : nums[b++];
        }
        while(a <= m) tmp[i++] = nums[a++];
        while(b <= r) tmp[i++] = nums[b++];
        for(i = l; i <= r; ++i) nums[i] = tmp[i];

        return ret;
    }

    long long count(vector<int>& nums, int l, int r)
    {
        if(l >= r) return 0;
        int m = l + ((r - l) >> 1);
        return count(nums, l, m) + count(nums, m + 1, r) + merge(nums, l, m, r);
    }

public:
    long long numberOfPairs(vector<int>& a, vector<int>& nums2, int d) 
    {
        int n = a.size();
        diff = d;
        for(int i = 0; i < n; ++i) a[i] -= nums2[i];
        return count(a, 0, n - 1);
    }
};